package id.net.iconpln.bb.client;


import id.net.iconpln.bb.client.service.LoginService;
import id.net.iconpln.bb.client.service.LoginServiceAsync;

import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.KeyListener;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class Login extends Dialog{
	  private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";
	  private final LoginServiceAsync loginService = GWT.create(LoginService.class);
	  protected TextField<String> userName;
	  protected TextField<String> password;
	  protected Button reset;
	  protected Button login;
	  protected Status status;

	  public Login() {
	    FormLayout layout = new FormLayout();	    
	    layout.setLabelWidth(90);
	    layout.setDefaultWidth(155);
//	    layout.set
//	    center();
	    setLayout(layout);
	    
	    setDraggable(false);
	    setClosable(false);
	    setButtonAlign(HorizontalAlignment.LEFT);
	    setButtons("");
//	    setIcon(IconHelper.createStyle("user"));
	    setHeading("Login");
	    setModal(true);
	    setBodyBorder(true);
	    setBodyStyle("padding: 8px;background: none");
	    setWidth(300);
	    setSize(300,150);
	    setResizable(false);
	    

	    KeyListener keyListener = new KeyListener() {
	      public void componentKeyUp(ComponentEvent event) {
	    	  if (event.getKeyCode() == 13 && login.isEnabled()) {
					onSubmit();
				}
				validate();

	      }

	    };

	    userName = new TextField<String>();
	    userName.setMinLength(3);
	    userName.setFieldLabel("Username");
	    userName.addKeyListener(keyListener);
	    add(userName);

	    password = new TextField<String>();
	    password.setMinLength(4);
	    password.setPassword(true);
	    password.setFieldLabel("Password");
	    password.addKeyListener(keyListener);
//	    password.addListener(Events.KeyUp, new Listener<FieldEvent>() {
//
//			@Override
//			public void handleEvent(FieldEvent be) {
//				// TODO Auto-generated method stub
//				if (be.getKeyCode() == "13"){
//					onSubmit();
//				}
//			}
//	    	
//		});
//	    

	    add(password);

	    setFocusWidget(userName);

	  }

	  @Override
	  protected void createButtons() {
	    super.createButtons();
	    status = new Status();
	    status.setBusy("please wait...");
	    status.hide();
	    status.setAutoWidth(true);
	    getButtonBar().add(status);
	    
	    getButtonBar().add(new FillToolItem());
	    
	    reset = new Button("Reset");
	    reset.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {
	        userName.reset();
	        password.reset();
	        validate();
	        userName.focus();
	      }

	    });

	    login = new Button("Login");
	    login.disable();
	    login.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      public void componentSelected(ButtonEvent ce) {
	        onSubmit();
	      }
	    });

	    addButton(reset);
	    addButton(login);

	    
	  }

	  protected void onSubmit() {
		GWT.log("load onSubmit", null);
	    status.show();
	    getButtonBar().disable();
	    
	    Timer t = new Timer() {
	      @Override
	      public void run() {
	    	  validasiLogins();
//	    	  MessageBox.alert("Info", "Terima kasih <b>" + userName.getValue() + "</b>", new Listener<MessageBoxEvent>() {
//
//				@Override
//				public void handleEvent(MessageBoxEvent be) {
//					// TODO Auto-generated method stub
//					   Button btn = be.getButtonClicked();
//			    	   GWT.log(btn.getText(), null);
////			    	   if (btn.getText() == "Ok"){
////			    		    Login.this.hide();
////			    		    GXT.hideLoadingPanel("loading");
////							redirect(GWT.getHostPageBaseURL()+ "Main.html");
////							return;
////			    	   }
//			    	   validasiLogins();
					status.hide();
					getButtonBar().enable();	
//				}
//			});
	      }

	    };
	    t.schedule(2000);
	  }

	  protected boolean hasValue(TextField<String> field) {
	    return field.getValue() != null && field.getValue().length() > 0;
	  }

	  protected void validate() {
	    login.setEnabled(hasValue(userName) && hasValue(password)
	        && password.getValue().length() > 3);
	  }
	  private void validasiLogins(){
			String userField = userName.getValue().toUpperCase();
			String passField = password.getValue();
////			LoginServiceAsync LoginService = GWT.create(LoginService.class);
//			
			loginService.loginServer(userField,passField,new AsyncCallback<String>() {
			      		@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("Error", SERVER_ERROR, null);
						}
						@Override
						public void onSuccess(String result) {							
//							String r = result.substring(0,5);
							final String[] words = result.split (";");
							for (int i=0; i < words.length; i++){
								GWT.log("num of str " + i +"= " +words[i],null);
							} 	

							
							GWT.log("hasil " + result, null);
							if (words[0].equals("SUKSES")){
								MessageBox.alert("Login Information", "Login "+ words[0] + " Press OK", 
										new Listener<MessageBoxEvent>() {  
									       public void handleEvent(MessageBoxEvent ce) {
									    	   
									    	   Button btn = ce.getButtonClicked();//
//									    	   Registry.register("isModule", words[1]);
									    	   GWT.log(btn.getText(), null);
									    	   if (btn.getText().equals("OK")){
									    		    Login.this.hide();
									    		    GXT.hideLoadingPanel("loading");
													redirect(GWT.getHostPageBaseURL()+ "Main.html");
													return;
									    	   }
									       }

										
								}); 

							}else{
								
									MessageBox.alert("Login Information", "Data Login Salah Press OK", 
										  new Listener<MessageBoxEvent>() {  
									       public void handleEvent(MessageBoxEvent ce) {  
//										         Button btn = ce.getButtonClicked();  
//										         Info.display("MessageBox", "The '{0}' button was pressed", btn.getText());  
//									    	   		AppEvent appEvent = new AppEvent(AppEvents.Login);												    
//										      	    Dispatcher.forwardEvent(appEvent);
//														Dispatcher.forwardEvent();
//														LoginDialog.this.show();
									    	   
//									    	   		if (result.equals("SUKESS")){
//									    	   			redirect(GWT.getHostPageBaseURL()+ "Main.html");
//														return;
//									    	   		}else{
									    	   			getButtonBar().enable();
//									    	   		}
												    status.hide();
												    GXT.hideLoadingPanel("loading");
													
												    
									       	}										       
									 });  
										       
							      

							}
						
						}
						
					});

	  }
		native void redirect(String url)
		/*-{
			$wnd.location.replace(url);
		}-*/;
		}